// cloudfunctions/getCommunityPosts/index.js
const cloud = require('wx-server-sdk');
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
});
const db = cloud.database();
const _ = db.command;

exports.main = async (event, context) => {
  try {
    const { 
      page = 1, 
      pageSize = 10, 
      productId = '',
      sortField = 'time', // 排序字段: like/comment/time
      sortDirection = 'desc' // 排序方向: asc/desc
    } = event;
    const skip = (page - 1) * pageSize;
    
    // 构建查询条件
    const query = {};
   
    
    // 定义排序规则映射
    const sortRules = {
      like: { field: 'likeCount', direction: sortDirection },
      comment: { field: 'commentCount', direction: sortDirection },
      time: { field: 'createTime', direction: sortDirection }
    };
    
    // 获取排序配置
    const { field, direction } = sortRules[sortField] || sortRules.time;
    
    // 查询帖子列表（先按时间排序获取所有数据，再内存排序实现三维排序）
    const postsResult = await db.collection('community_posts')
      .where(query)
      .orderBy('createTime', 'desc') // 先按时间获取所有数据
      .get();
    console.log(postsResult);
    const allPosts = postsResult.data;
    
    // 三维排序逻辑
    const sortedPosts = allPosts.sort((a, b) => {
      // 1. 按选择的主字段排序
      let result = direction === 'desc' 
        ? b[field] - a[field] 
        : a[field] - b[field];
      
      if (result !== 0) return result;
      
      // 2. 次排序：点赞数
      result = direction === 'desc' 
        ? b.likes - a.likes 
        : a.likes - b.likes;
      
      if (result !== 0) return result;
      
      // 3. 第三排序：评论数
      result = direction === 'desc' 
        ? b.comments - a.comments 
        : a.comments - b.comments;
      
      if (result !== 0) return result;
      
      // 4. 最终排序：时间
      return direction === 'desc' 
        ? new Date(b.createTime) - new Date(a.createTime) 
        : new Date(a.createTime) - new Date(b.createTime);
    });
    
    // 分页处理
    const start = skip;
    const end = skip + pageSize;
    const paginatedPosts = sortedPosts.slice(start, end);
    
    // 查询点赞状态（如果已登录）
    const userInfo = cloud.getWXContext().USER_INFO;
    let likeStatus = {};
    
    if (userInfo) {
      const likesResult = await db.collection('user_likes')
        .where({
          userId: userInfo._id,
          type: 'post',
          itemId: _.in(paginatedPosts.map(post => post._id))
        })
        .get();
      
      likesResult.data.forEach(like => {
        likeStatus[like.itemId] = true;
      });
    }
    
    return {
      success: true,
      data: {
        posts: paginatedPosts.map(post => ({
          ...post,
          isLiked: likeStatus[post._id] || false
        })),
        total: allPosts.length,
        page,
        pageSize,
        sortField,
        sortDirection
      },
      message: '获取帖子列表成功'
    };
  } catch (error) {
    console.error('获取帖子列表失败', error);
    return {
      success: false,
      message: error.message || '服务器错误',
      error: error.message
    };
  }
};